package cn.novate.jetpackdemo.workmanager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.novate.jetpackdemo.R;

public class WorkManagerMainActivity extends AppCompatActivity {

    private final static String TAG = WorkManagerMainActivity.class.getCanonicalName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_manager_main);
    }

    public void workManager0(View view) {
        Log.e(TAG, " 简单任务 开始执行了。。。。。");
        // 对简单任务进行包装
        OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(UploadWorker.class).build();
        WorkManager.getInstance(getApplicationContext()).enqueue(oneTimeWorkRequest);


    }

    public void workManager01(View view) {

        Log.e(TAG, " 简单任务 开始执行了  向 WorkMain传递参数。。。。。");
        Map map = new HashMap();
        map.put("dataMian", "把我传递给WorkMain");
        //  传递参数   到 任务   必须以  键值对的来传递
        @SuppressLint("RestrictedApi")
        Data sendData = new Data(map);
        OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(WorkMain.class)
                .setInputData(sendData)
                .build();

        //接收返回来的数据
        WorkManager.getInstance(getApplicationContext()).getWorkInfoByIdLiveData(oneTimeWorkRequest.getId())
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {//  系统会轮询调用次数（多次），有时候两次有时候三次不

                        Log.e(TAG, " 我接收到回传的数据了。。。。。" + workInfo.getOutputData().getString("dataMian2"));
                        Log.e(TAG, " 状态。。。。。" + workInfo.getState());
                        if (workInfo.getState().isFinished()) {
                            Log.e(TAG, " 接收到回传数据的任务已经完成了。。。。。isFinished = true" + workInfo.getOutputData().getString("dataMian2"));
                        }
                    }
                });
        //  请求对象  加入到队列里面去
        WorkManager.getInstance(getApplicationContext()).enqueue(oneTimeWorkRequest);
    }

    //TODO 多任务执行
    public void workManager02(View view) {

        Log.e(TAG, " 点击了多任务执行按钮。。。。。");
        //  每个OneTimeWorkRequest  都可以做各自的任务
        OneTimeWorkRequest oneTimeWorkRequest01 = new OneTimeWorkRequest.Builder(UploadWorker01.class).build();
        OneTimeWorkRequest oneTimeWorkRequest02 = new OneTimeWorkRequest.Builder(UploadWorker02.class).build();
        OneTimeWorkRequest oneTimeWorkRequest03 = new OneTimeWorkRequest.Builder(UploadWorker03.class).build();
        OneTimeWorkRequest oneTimeWorkRequest04 = new OneTimeWorkRequest.Builder(UploadWorker04.class).build();

        List<OneTimeWorkRequest> list = new ArrayList<>();
        list.add(oneTimeWorkRequest01);
        list.add(oneTimeWorkRequest02);
        list.add(oneTimeWorkRequest03);
        //  优先执行集合的再执行后面的
        WorkManager.getInstance(getApplicationContext()).beginWith(list)//  执行集合里面的数据也没有按顺序来，随机来执行的
                .then(oneTimeWorkRequest04)
                .enqueue();

    }

    //TODO  约束条件
    public void workManager03(View view) {
        Log.e(TAG, " 点击了时间约束条件来执行按钮。。。。。");


        // 重复的任务  多次  循环  最少中间间隔  15  分钟 执行一次
        PeriodicWorkRequest periodicWorkRequest =//            只要传入的时间小于或者等于 15  分钟都是默认  15  分钟执行一次
                new PeriodicWorkRequest.Builder(UploadWorker04.class, 5, TimeUnit.SECONDS).build();
        //  测试： 监听状态
        WorkManager.getInstance(this).getWorkInfoByIdLiveData(periodicWorkRequest.getId())
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {
                        Log.e(TAG, " 状态。。。。。" + workInfo.getState());
                        if (workInfo.getState().isFinished()) {
                            Log.e(TAG, " 。。。。。isFinished = true  后台任务已经执行完成了");
                        }
                    }
                });
        WorkManager.getInstance(getApplicationContext()).enqueue(periodicWorkRequest);
    }

    // TODO 其它约束条件
    public void workManager04(View view) {

        //  约束条件
        @SuppressLint("IdleBatteryChargingConstraints")
        Constraints myConstraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)//是否网络连接中
                .setRequiresCharging(true)//是否充电中
                .setRequiresDeviceIdle(true)// 设备是否为空闲中
                .setRequiresStorageNotLow(true)//   设备可用存储是否低于临界阈值
                .setRequiresBatteryNotLow(true)//  设备是否为低电量时运行
                .build();
      //  请求对象
        OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(UploadWorker04.class)
                .setConstraints(myConstraints)
                .build();

        // 加入队列
        WorkManager.getInstance(getApplicationContext()).enqueue(oneTimeWorkRequest);
    }
}